package thread;

public class Race {

    public static void main(String[] args) {
        new Thread(new RabbitAndTurtle(),"乌龟").start();
        new Thread(new RabbitAndTurtle(),"兔子").start();
    }
}

class RabbitAndTurtle implements Runnable{

    /**
     * 赛跑的总长度
     */
    private int length = 100;

    /**
     * 计数器
     */
    private int preLenth = 0;


    private static volatile boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (Thread.currentThread().getName().equals("乌龟")) {
                    preLenth++;
                    System.out.println(Thread.currentThread().getName() + "跑了:" + preLenth + "米");
                    if (preLenth == length) {
                        System.out.println(Thread.currentThread().getName() + "跑赢了");
                        flag = false;
                        break;
                    }

            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (Thread.currentThread().getName().equals("兔子")) {
                preLenth = preLenth + 2;
                    System.out.println(Thread.currentThread().getName() + "跑了:" + preLenth + "米");

                    if (preLenth>60){
                        try {
                            System.out.println(Thread.currentThread().getName() + "开始骄傲了，准备休息......");
                            Thread.sleep(60*1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (preLenth == length) {
                        System.out.println(Thread.currentThread().getName() + "跑赢了");
                        flag = false;
                        break;
                    }

            }
        }
    }
}
